﻿//Force setting jQuery support cross domain.
//This line mostly has effective in IE
jQuery.support.cors = true;
var userId = "";
userId = readCookie("userId");
if (userId == "") {
    window.location.href = '../Profile/Login?ref=' + getCurrentPage();
}
// Get Value CheckBox
jQuery.fn.getCheckboxVal = function () {
    var vals = [];
    var i = 0;
    this.each(function () {
        vals[i++] = jQuery(this).val();
    });
    return vals;
}
// Get Value CheckBox

// Get name CheckBox
jQuery.fn.getCheckboxName = function () {
    var names = [];
    var i = 0;
    this.each(function () {
        names[i++] = jQuery(this).attr('name');
    });
    return names;
}
// Get name CheckBox

// globaldata of alert page
var selectedRowKey = ""; // row's id is current selected in list 
var arrData = new Array(); // all infomation get from service
var alertFilter = new Object(); //alert filter object
var alertnames = new Array();
var messagebodys = new Array();
var campaignids = new Array();
var countryids = new Array();
var languageids = new Array();

$(document).ready(function () {
    $('select.select_long').customStyle();

    function getAlertInstanceList() {
        // Json: Get Alert List
        var alertFilter = new Object();
        alertFilter.userid = userId;
        arrData = new Array();
        $.ajax({
            url: gb_servicePath + '/alertinstance/list/summary.json',
            crossDomain: "true",
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            traditional: true,
            data: JSON.stringify(alertFilter),
            dataType: 'json',
            success: function (data) {
                if (data.StatusCode == 200) {
                    $.each(data.ReturnData, function (i, val) {
                        var o = new Object();
                        o.id = val.ID;
                        o.collectionId = val.AlertCollectionSummary.Id;
                        if (val.IsActive == 1) {
                            o.active = "true";
                        }
                        else {
                            o.active = "false";
                        }
                        if (val.AlertCollectionSummary.ApprovalStatus.Name == "Draft") {
                            o.draft = "true";
                        } else {
                            o.draft = "false";
                        }
                        var frequency = "";
                        if (val.AlertCollectionSummary.FrequencySettings.length > 0) {
                            var Timeunitid = val.AlertCollectionSummary.FrequencySettings[0].Timeunitid;
                            switch (Timeunitid) {
                                case 1:
                                    frequency = "Minute";
                                    break;
                                case 2:
                                    frequency = "Hour";
                                    break;
                                case 3:
                                    frequency = "Daily";
                                    break;
                                case 4:
                                    frequency = "Week";
                                    break;
                                case 5:
                                    frequency = "Month";
                                    break;
                                case 6:
                                    frequency = "Year";
                                    break;
                            }
                        }
                        else {
                            frequency = "None";
                        }
                        o.frequency = frequency;

                        var start_time = val.SendDate.substr(6).replace(')', '').replace('/', '');
                        start_time = new Date(parseInt(start_time));
                        start_time = start_time.getFullYear() + '/' + format2Digi(start_time.getMonth() + 1) + '/' + format2Digi(start_time.getDate());

                        o.date = start_time;
                        o.name = val.Name;
                        o.campaign = val.CampaignSummary.Name;
                        arrData.push(o);
                        //shtml += '<div id="' + i + '" class="rows_alert clear"><div class="col_date">' + month + '/' + year + '</div><div class="col_name">' + val.Name + '</div><div class="col_campaign">' + val.Alertcollection.Campaign.Name + '</div><div class="col_frequency">' + frequency + '</div><div class="colo_draft">' + draft + '</div><div class="col_active">' + active + '</div><div class="bar hide"><a class="i_edit marginRgt05" href="/Alert/NewAlert?action=edit">Edit</a><a class="i_copy marginRgt05" href="">Copy</a><a class="i_delete marginRgt10 jqModal" href="#"> Delete</a></div></div>';

                    });

                    bindData();
                    SortAlertFilter("date", 1);
                    getListCampain();
                }
            },
            error: function (jqXHR, textStatus, xerror) {
                if (isBug) {
                    alert("Error in " + gb_servicePath + " alertinstance/list/summary.json ->" + xerror);
                }
            }
        });
    }
    // End Json: Get Alert List

    // Bind Data
    function bindData() {

        $(".list_row_alert").find("img").hide();
        $(".list_row_alert").find(".rows_alert").each(function () {
            $(this).remove();
        });

        for (var i = 0; i < arrData.length; i++) {
            var o = $("#form_rows_temp").clone();
            $(o).attr("id", arrData[i].id);
            $(o).attr("collectionid", arrData[i].collectionId);
            $(o).removeClass("item_temp");
            if (i % 2 == 1) {
                $(o).addClass("alert_alt");
            }
            $(o).find(".col_date").html(arrData[i].date);
            $(o).find(".col_name").html(arrData[i].name);
            $(o).find(".col_campaign").html(arrData[i].campaign);
            $(o).find(".col_frequency").html(arrData[i].frequency);
            if (arrData[i].draft == "true") {
                $(o).find(".colo_draft").html('<span class="active"></span>');
            }
            if (arrData[i].active == "true") {
                $(o).find(".col_active").html('<span class="active"></span>');
            }
            if (selectedRowKey == arrData[i].id.toString()) {
                $(o).addClass('rows_alert_hover');
                $(o).find('.bar').removeClass("hide");
            }

            if ($(".list_row_alert").find(".jspPane").size() == 0) {
                $(".list_row_alert").append(o);
            } else {
                $(".list_row_alert").find(".jspPane").append(o);
            }
        }
        $(".i_delete").click(function () {
            showModal(true);
        });
        $(".i_copy").click(function () {
            window.location.href = 'NewAlert?action=' + selectedRowKey + '#copy'; ;
        });
        $(".i_edit").click(function () {
            window.location.href = 'NewAlert?id=' + selectedRowKey;
        });


        $('.rows_alert').click(function () {
            $('.rows_alert').removeClass('rows_alert_hover');
            $(this).addClass('rows_alert_hover');
            $('#view_summary').removeClass('hide');
            selectedRowKey = $(this).attr("id");
            $('.bar').addClass('hide');
            $(this).find('.bar').removeClass('hide');
            $('.cal_select').removeClass('rows_alert_hover_daysummary');
            $('.list_row_alert').jScrollPane({ animateScroll: true });
            $('#content_mess').jScrollPane({ animateScroll: true });
            GetDetailSummary(selectedRowKey);
        });
        $('.btn_close').click(function (e) {
            $("#view_summary").addClass('hide');
            $('.bar').addClass('hide');
            $('.rows_alert').removeClass('rows_alert_hover');
            return false;
        });
        $('.list_row_alert').jScrollPane({ animateScroll: true });
    }
    // End Bind Data
    
    // Function Get Detail Summary
    function GetDetailSummary(id) {
        $.getJSON(gb_servicePath + '/alertinstance/ID/' + id + '.json',
            {},
            function (json) {
                if (json.StatusCode == 200) {
                    var shtml = '';
                    var data = json.ReturnData;
                    $('#header_box_super_admin').html(data.Name.substring(0, 21));
                    $('#campaign_name').html(data.AlertInstanceSummary.CampaignSummary.Name);

                    var start_time = data.AlertInstanceSummary.AlertCollectionSummary.StartTime.substr(6).replace(')', '').replace('/', '');
                    var end_time = data.AlertInstanceSummary.AlertCollectionSummary.EndTime.substr(6).replace(')', '').replace('/', '');
                    //alert(parseInt(date));05/01/2011 15:36
                    start_time = new Date(parseInt(start_time));
                    start_time = format2Digi(start_time.getMonth() + 1) + '/' + format2Digi(start_time.getDate()) + '/' + start_time.getUTCFullYear() + ' ' + format2Digi(start_time.getUTCHours()) + ':' + format2Digi(start_time.getUTCMinutes());
                    end_time = new Date(parseInt(end_time));
                    end_time = format2Digi(end_time.getMonth() + 1) + '/' + format2Digi(end_time.getDate()) + '/' + end_time.getUTCFullYear() + ' ' + format2Digi(end_time.getUTCHours()) + ':' + format2Digi(end_time.getUTCMinutes());
                    $('#start_date').html(start_time);
                    $('#end_date').html(end_time);

                    var frequency = "";
                    if (data.AlertInstanceSummary.AlertCollectionSummary.FrequencySettings.length > 0) {
                        var Timeunitid = data.AlertInstanceSummary.AlertCollectionSummary.FrequencySettings[0].Timeunitid;
                        switch (Timeunitid) {
                            case 1:
                                frequency = "Minute";
                                break;
                            case 2:
                                frequency = "Hour";
                                break;
                            case 3:
                                frequency = "Daily";
                                break;
                            case 4:
                                frequency = "Week";
                                break;
                            case 5:
                                frequency = "Month";
                                break;
                            case 6:
                                frequency = "Year";
                                break;
                        }
                    }
                    else {
                        frequency = "None";
                    }
                    $('#recurring').html(frequency);

                    //$('#countries').html(data.Alertcollection.Preference.each(data.Alertcollection.Preference, function (country) { return country.Name + ', ' }))
                    var country = "";
                    var countryIds = "";
                    var delivery = "";
                    var deliveryIds = "";
                    $.each(data.AlertInstanceSummary.AlertCollectionSummary.Preference, function (i, val) {
                        if (countryIds.indexOf(val.Preference.Country.Id) == -1) {
                            country += val.Preference.Country.Name + " ( " + val.Preference.Language.Name + " ) " + "<br/>"
                            countryIds += val.Preference.Country.Id + ",";
                        }
                        if (deliveryIds.indexOf(val.Media.Id) == -1) {
                            delivery += val.Media.Name + ",";
                            deliveryIds += val.Media.Id + ",";
                        }
                    });

                    $('#countries').html(country);
                    $('#delivery').html(delivery.substring(0, delivery.length - 1));
                    var audience = "";
                    $.each(data.Alertcollection.Audience, function (i, val) {
                        audience += val.Name + ",";
                    })
                    $("#audience").html(audience.substring(0, audience.length - 1));


                    $(".messagesTemplate").css("display", "none");
                    $.each(data.AlertInstanceSummary.MessageFlows, function (i1, val1) {
                        var o = $(".messagesTemplate").clone();
                        $(o).removeClass("messagesTemplate");
                        $(o).addClass('list_mess_main');
                        $(o).css("display", "block");
                        $(o).attr('id', 'id' + val1.Id);
                        $(o).find(".lblMessage").html(val1.Country.Name + '/' + val1.Language.Name + '/' + val1.Media.Name);
                        $(o).find(".lbl_content_mess").html(val1.Messagebody);

                        $.each(val1.KeywordIDList, function (i2, val2) {
                            var id = val2;
                            var str = "";
                            $.getJSON(gb_servicePath + '/keyword/ID/' + id + '.json',
                                {},
                                function (json) {
                                    if (json.StatusCode == 200) {
                                        var data = json.ReturnData;
                                        str = str + "<div class=\"list_keyword_main\"><table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"100%\">" +
                                        "<tr><td><b>Keyword</b></td><td class=\"lblKeyword\">" + data.Name + "</td></tr>";
                                        $.each(data.Audience, function (i3, val3) {
                                            str = str + "<tr><td><b>Audience</b></td><td class=\"lblAudience\">" + val3.Name + "</td></tr>";
                                        });
                                        str = str + "</table><div class=\"list_mess_type\">";
                                        $.each(data.FollowUpMessageFlowList, function (i4, val4) {
                                            str = str + "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"100%\"><tr><td width=\"100%\">" +
                                            "<b class=\"lbl_for_mess_type\">Message for Message Type " + (i4 + 1) + "</b>" +
                                            "<div id=\"contentMessageType\" class=\"contentMessageType\">" + val4.Messagebody +
                                            "</div></td></tr>";
                                        });
                                        str = str + "</div></div>";
                                        $('#id' + val1.Id + ' .list_keyword').append(str);
                                    }

                                });
                            //$('.list_keyword').html(str);
                        });

                        $("#content_mess .jspPane").append(o);
                        $('#content_mess').jScrollPane({ animateScroll: true });
                        $('.expand_mess_flow').click(function () {
                            $(this).addClass('hide');
                            $(this).next().removeClass('hide');
                            $(this).prev().removeClass('hide');
                            $('#content_mess').jScrollPane({ animateScroll: true });
                        });
                        $('.collapse_mess_flow').click(function () {
                            $(this).addClass('hide');
                            $(this).prev().removeClass('hide');
                            $(this).prev().prev().addClass('hide');
                            $('#content_mess').jScrollPane({ animateScroll: true });
                        });

                    });

                }
            }
            );
    }

    // Function Get List Campain
    function getListCampain() {
        $("#listCampainTemplate").css("display", "none");
        $.getJSON(gb_servicePath + '/campaign/list/summary.json',
                function (json1) {
                    if (json1.StatusCode == 200) {
                        $.each(json1.ReturnData, function (i, val) {
                            var o = $("#listCampainTemplate").clone();
                            $(o).css("display", "block");
                            $(o).find("input").attr("value", val.Name);
                            $(o).find("input").attr("name", val.Id);
                            $(o).find("input").addClass("case_main");
                            $(o).attr("id", val.Id);
                            $(o).find("span").html(val.Name);
                            $(".list_campaign_cb").append(o);
                        });
                        $('.label_check, .label_radio, .label_check_ip').click(function () {
                            setupLabel();
                        });
                        $('.list_campaign_cb').jScrollPane();
                    }
                    getListCountries();
                });
    }
    // End Function Get List Campain

    // Get Function Get List Countries
    function getListCountries() {
        $("#listCountriesTemplate").css("display", "none");
        $("#listLanguageTemplate").css("display", "none");
        $.getJSON(gb_servicePath + '/countrypreference/list.json',
                function (json1) {
                    if (json1.StatusCode == 200) {
                        var strLangIdAdded = "";
                        var langId;
                        $.each(json1.ReturnData, function (i, val) {
                            // check if alredy add country in combobox
                            if ($("#country" + val.Country.Id).length == 0) {
                                var o = $("#listCountriesTemplate").clone();
                                $(o).css("display", "block");
                                $(o).find("input").attr("value", val.Country.Name);
                                $(o).find("input").attr("name", val.Country.Id);
                                $(o).find("input").addClass("case_main");
                                $(o).attr("id", "country" + val.Country.Id);
                                $(o).attr("value", val.Country.Id);
                                $(o).find("span").html(val.Country.Name);
                                $(".countries #list_countries").append(o);
                                langId = val.Language.Id;
                            } if (strLangIdAdded.indexOf(langId) < 0) {
                                //hasn't added langId yet
                                var olag = $("#listLanguageTemplate").clone();
                                olag.css("display", "block");
                                olag.find("input").attr("value", val.Language.Name);
                                olag.find("input").attr("name", val.Language.Id);
                                olag.find("input").addClass("case_main");
                                olag.attr("id", val.Language.Id);
                                olag.attr("name", val.Language.Id);
                                olag.find("span").html(val.Language.Name);
                                $(".list_language").append(olag);
                                strLangIdAdded += langId + ";";
                            }
                        });
                        $('.label_check, .label_radio, .label_check_ip').click(function () {
                            setupLabel();
                        });
                        $('.list_countries').jScrollPane();
                    }
                });
    }
    // End Get Function Get List Countries

    // Json: Get Alert List
    function bindDataByFilter() {

        $(".list_row_alert").find("img").show();
        $(".list_row_alert .rows_alert").hide();
        $('.list_row_alert').jScrollPane({ animateScroll: true });
        $.ajax({
            url: gb_servicePath + '/alertinstance/list/summary.json',
            crossDomain: "true",
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            traditional: true,
            data: JSON.stringify(alertFilter),
            "dataType": 'json',
            success: function (data) {
                if (data.StatusCode == 200) {
                    $(".list_row_alert").find("img").hide();
                    $(".list_row_alert .rows_alert").show();
                    arrData = new Array();
                    $.each(data.ReturnData, function (i, val) {
                        var o = new Object();
                        o.id = val.ID;
                        if (val.IsActive == 1) {
                            o.active = "true";
                        }
                        else {
                            o.active = "false";
                        }
                        var frequency = "";
                        if (val.AlertCollectionSummary.FrequencySettings.length > 0) {
                            var Timeunitid = val.AlertCollectionSummary.FrequencySettings[0].Timeunitid;
                            switch (Timeunitid) {
                                case 1:
                                    frequency = "Minute";
                                    break;
                                case 2:
                                    frequency = "Hour";
                                    break;
                                case 3:
                                    frequency = "Daily";
                                    break;
                                case 4:
                                    frequency = "Week";
                                    break;
                                case 5:
                                    frequency = "Month";
                                    break;
                                case 6:
                                    frequency = "Year";
                                    break;
                            }
                        }
                        else {
                            frequency = "None";
                        }
                        o.frequency = frequency;

                        var date = val.SendDate.substr(6).replace(')', '').replace('/', '');
                        var sendTime = new Date(parseInt(date));
                        var month = sendTime.getMonth() + 1;
                        if (month < 9) {
                            month = '0' + (sendTime.getMonth() + 1);
                        }
                        var day = sendTime.getDate();
                        if (day < 9) {
                            day = '0' + (sendTime.getDate());
                        }
                        o.date = sendTime.getFullYear() + "/" + month + "/" + day;
                        o.name = val.AlertCollectionSummary.Name;
                        o.campaign = val.CampaignSummary.Name;
                        arrData.push(o);
                    });

                    bindData();
                }
            },
            error: function (jqXHR, textStatus, xerror) {
                if (isBug) {
                    alert("Error in " + gb_servicePath + " alertinstance/list/summary.json -> " + xerror);
                }
            }
        });
    }

    // Function Sort Alert
    function SortAlertFilter(str, index) {
        //$.fancybox.close();

        arrData = arrData.objSort(str, index);
        $(".list_row_alert").find(".rows_alert").each(function () {
            $(this).remove();
        });
        for (var i = 0; i < arrData.length; i++) {
            var o = $("#form_rows_temp").clone();
            $(o).attr("id", arrData[i].id);
            $(o).attr("collectionid", arrData[i].collectionId);
            if (i % 2 == 1) {
                $(o).addClass("alert_alt");
            }
            $(o).removeClass("item_temp");
            $(o).find(".col_date").html(arrData[i].date);
            $(o).find(".col_name").html(arrData[i].name);
            $(o).find(".col_campaign").html(arrData[i].campaign);
            $(o).find(".col_frequency").html(arrData[i].frequency);
            if (arrData[i].draft == "true") {
                $(o).find(".colo_draft").html('<span class="active"></span>');
            }
            if (arrData[i].active == "true") {
                $(o).find(".col_active").html('<span class="active"></span>');
            }
            if (selectedRowKey == arrData[i].id.toString()) {
                $(o).addClass('rows_alert_hover');
                $(o).find('.bar').removeClass("hide");
            }
            if ($(".list_row_alert").find(".jspPane").size() == 0) {
                $(".list_row_alert").append(o);
            } else {
                $(".list_row_alert").find(".jspPane").append(o);
            }
        }
        $(".i_delete").click(function () {
            showModal(true);
        });
        $(".i_copy").click(function () {
            window.location.href = 'NewAlert?id=' + selectedRowKey+'#copy';
        });
        $(".i_edit").click(function () {
            window.location.href = 'NewAlert?id=' + selectedRowKey;
        });

        $('.rows_alert').click(function () {// show sumary popup
            $('.rows_alert').removeClass('rows_alert_hover');
            $(this).addClass('rows_alert_hover');
            $('#view_summary').removeClass('hide');
            $('#view_summary').css('margin-top', '49px');
            selectedRowKey = $(this).attr("id");
            $('.bar').addClass('hide');
            $(this).find('.bar').removeClass('hide');
            $('.cal_select').removeClass('rows_alert_hover_daysummary');
            $('.list_mess_main').remove();
            GetDetailSummary(selectedRowKey);
            $('.list_row_alert').jScrollPane({ animateScroll: true });
            $('#content_mess').jScrollPane({ animateScroll: true });
        });

        $('.btn_close').click(function (e) {
            $("#view_summary").addClass('hide');
            $('.bar').addClass('hide');
            $('.rows_alert').removeClass('rows_alert_hover');
            $('.cal_select').removeClass('rows_alert_hover_daysummary');
            $('.list_row_alert').jScrollPane({ animateScroll: true });
            return false;
        });

        $('.list_row_alert').jScrollPane({ animateScroll: true });
    }
    // End Function Sort Alert

    getAlertInstanceList();

    // Bind event click Sort By Name
    $("#btSortName").find("img").css("visibility", "hidden");
    $("#btSortName").click(function () {
        SortAlertFilter("name", -1 * parseInt($("#btSortName").attr("sort")));
        $("#btSortName").attr("sort", -1 * parseInt($("#btSortName").attr("sort")));

        $("#btSortName").find("img").css("visibility", "visible");
        $("#btSortDate").find("img").css("visibility", "hidden");
        $("#btSortCampaign").find("img").css("visibility", "hidden");
        $("#btSortFrequency").find("img").css("visibility", "hidden");
        $("#btSortDraft").find("img").css("visibility", "hidden");
        $("#btSortActive").find("img").css("visibility", "hidden");
        if ($("#btSortName").attr("sort") == 1) {
            $("#btSortName").find("img").rotate(180);
        } else {
            $("#btSortName").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Name

    // Bind event click Sort By Date
    $("#btSortDate").find("img").rotate(180);
    $("#btSortDate").click(function () {
        SortAlertFilter("date", -1 * parseInt($("#btSortDate").attr("sort")));
        $("#btSortDate").attr("sort", -1 * parseInt($("#btSortDate").attr("sort")));

        $("#btSortName").find("img").css("visibility", "hidden");
        $("#btSortDate").find("img").css("visibility", "visible");
        $("#btSortCampaign").find("img").css("visibility", "hidden");
        $("#btSortFrequency").find("img").css("visibility", "hidden");
        $("#btSortDraft").find("img").css("visibility", "hidden");
        $("#btSortActive").find("img").css("visibility", "hidden");
        if ($("#btSortDate").attr("sort") == 1) {
            $("#btSortDate").find("img").rotate(180);
        } else {
            $("#btSortDate").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Date

    // Bind event click Sort By Campaign
    $("#btSortCampaign").find("img").css("visibility", "hidden");
    $("#btSortCampaign").click(function () {
        SortAlertFilter("campaign", -1 * parseInt($("#btSortCampaing").attr("sort")));
        $("#btSortCampaign").attr("sort", -1 * parseInt($("#btSortCampaign").attr("sort")));

        $("#btSortName").find("img").css("visibility", "hidden");
        $("#btSortDate").find("img").css("visibility", "hidden");
        $("#btSortCampaign").find("img").css("visibility", "visible");
        $("#btSortFrequency").find("img").css("visibility", "hidden");
        $("#btSortDraft").find("img").css("visibility", "hidden");
        $("#btSortActive").find("img").css("visibility", "hidden");
        if ($("#btSortCampaign").attr("sort") == 1) {
            $("#btSortCampaign").find("img").rotate(180);
        } else {
            $("#btSortCampaign").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Campaign

    // Bind event click Sort By Frequency
    $("#btSortFrequency").find("img").css("visibility", "hidden");
    $("#btSortFrequency").click(function () {
        SortAlertFilter("frequency", -1 * parseInt($("#btSortFrequency").attr("sort")));
        $("#btSortFrequency").attr("sort", -1 * parseInt($("#btSortFrequency").attr("sort")));

        $("#btSortName").find("img").css("visibility", "hidden");
        $("#btSortDate").find("img").css("visibility", "hidden");
        $("#btSortCampaign").find("img").css("visibility", "hidden");
        $("#btSortFrequency").find("img").css("visibility", "visible");
        $("#btSortDraft").find("img").css("visibility", "hidden");
        $("#btSortActive").find("img").css("visibility", "hidden");
        if ($("#btSortFrequency").attr("sort") == 1) {
            $("#btSortFrequency").find("img").rotate(180);
        } else {
            $("#btSortFrequency").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Frequency

    // Bind event click Sort By Draft
    $("#btSortDraft").find("img").css("visibility", "hidden");
    $("#btSortDraft").click(function () {
        SortAlertFilter("draft", -1 * parseInt($("#btSortDraft").attr("sort")));
        $("#btSortDraft").attr("sort", -1 * parseInt($("#btSortDraft").attr("sort")));

        $("#btSortName").find("img").css("visibility", "hidden");
        $("#btSortDate").find("img").css("visibility", "hidden");
        $("#btSortCampaign").find("img").css("visibility", "hidden");
        $("#btSortFrequency").find("img").css("visibility", "hidden");
        $("#btSortDraft").find("img").css("visibility", "visible");
        $("#btSortActive").find("img").css("visibility", "hidden");
        if ($("#btSortDraft").attr("sort") == 1) {
            $("#btSortDraft").find("img").rotate(180);
        } else {
            $("#btSortDraft").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Draft

    // Bind event click Sort By Active
    $("#btSortActive").find("img").css("visibility", "hidden");
    $("#btSortActive").click(function () {
        SortAlertFilter("active", -1 * parseInt($("#btSortActive").attr("sort")));
        $("#btSortActive").attr("sort", -1 * parseInt($("#btSortActive").attr("sort")));

        $("#btSortName").find("img").css("visibility", "hidden");
        $("#btSortDate").find("img").css("visibility", "hidden");
        $("#btSortCampaign").find("img").css("visibility", "hidden");
        $("#btSortFrequency").find("img").css("visibility", "hidden");
        $("#btSortDraft").find("img").css("visibility", "hidden");
        $("#btSortActive").find("img").css("visibility", "visible");
        if ($("#btSortActive").attr("sort") == 1) {
            $("#btSortActive").find("img").rotate(180);
        } else {
            $("#btSortActive").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Active
    // Bind Event Delete Alert 
    $('#btnOk_confirm2').click(function () {
        $.ajax({
            url: gb_servicePath + "/alertinstance/delete/" + selectedRowKey + ".json",
            crossDomain: "true",
            type: "POST", 'dataType': 'json',
            success: function (data) {
                if (data.StatusCode == 200) {
                    //  alert("Process retrieved data");
                    getAlertInstanceList();
                    $(".list_row_alert").find("img").show();
                    $(".list_row_alert").find(".rows_alert").each(function () {
                        $(this).remove();
                    });
                    $('#view_summary').addClass('hide');
                }

                showModal(false);
            },
            error: function (jqXHR, textStatus, xerror) {
                var response = jqXHR.responseText;

                showModal(false);
            }


        });
    });
    $('#btnOk_confirm3').click(function () {
        $.ajax({
            url: gb_servicePath + "/alertcollection/delete/" + $(".rows_alert_hover").attr("collectionid") + ".json",
            crossDomain: "true",
            type: "POST", 'dataType': 'json',
            success: function (data) {
                if (data.StatusCode == 200) {
                    getAlertInstanceList();
                    $(".list_row_alert").find("img").show();
                    $(".list_row_alert").find(".rows_alert").each(function () {
                        $(this).remove();
                    });
                    $('#view_summary').addClass('hide');
                }

                showModal(false);
            },
            error: function (jqXHR, textStatus, xerror) {
                var response = jqXHR.responseText;

                showModal(false);
            }


        });
    });
    // End Bind Event Delete Alert
    // Custom drop down list Countries
    $("#checkall").click(function () {
        $('.case.case_main').attr('checked', 'checked');
        setupLabel();
    });
    $("#clearall").click(function () {
        $('.case.case_main').removeAttr('checked');
        setupLabel();
    });
    $('.ddlcountries').hide();
    $('.countries').hide();
    $('.btn_countries').click(function (event) {
        event.stopPropagation();
        if ($('.countries').css('display') == 'none') {
            $('.countries').show();
            $('.list_countries').jScrollPane();
        } else {
            $('.countries').hide();
        }
        $(document).click(function () {
            if ($('.countries').css('display') != 'none') {
                $('.countries').hide();
            }
        });
        $('.countries').click(function (event) {
            event.stopPropagation();
        });
    });
    // End Custom drop down list Countries

    // Custom drop down list Campaign
    $("#checkallCampaign").click(function () {
        $('.case_campaign.case_main').attr('checked', 'checked');
        setupLabel();
    });
    $("#clearallCampaign").click(function () {
        $('.case_campaign.case_main').removeAttr('checked');
        setupLabel();
    });
    $('.ddlcampaign').hide();
    $('.campaign').hide();
    $('.btn_campaign').click(function (event) {
        event.stopPropagation();
        if ($('.campaign').css('display') == 'none') {
            $('.campaign').show();
            // scrollpane not apply when displaynone
            $('.list_campaign_cb').jScrollPane();
        } else {
            $('.campaign').hide();
        }
        $(document).click(function () {
            if ($('.campaign').css('display') != 'none') {
                $('.campaign').hide();
            }
        });
        $('.campaign').click(function (event) {
            event.stopPropagation();
        });

    });
    // End Custom drop down list Campaign

    // Custom drop down list Language
    $("#checkallLanguage").click(function () {
        $('.case_language.case_main').attr('checked', 'checked');
        setupLabel();
    });
    $("#clearallLanguage").click(function () {
        $('.case_language.case_main').removeAttr('checked');
        setupLabel();
    });
    $('.ddllanguage').hide();
    $('.language').hide();
    $('.btn_language').click(function (event) {
        event.stopPropagation();
        if ($('.language').css('display') == 'none') {
            $('.language').show();
            $('.list_language').jScrollPane();
        } else {
            $('.language').hide();
        }
        $(document).click(function () {
            if ($('.language').css('display') != 'none') {
                $('.language').hide();
            }
        });
        $('.language').click(function (event) {
            event.stopPropagation();
        });
    });
    // End Custom drop down list Language

    // Custom radio, checkbox and select
    $('body').addClass('has-js');
    $('.label_check, .label_radio, .label_check_ip').click(function () {
        setupLabel();
    });
    setupLabel();
    //    $('select.select_countries').customStyle();
    //    $('select.select_short2').customStyle();
    // End Custom radio, checkbox and select

    // call box_confirm
    $('#box_confirm').jqm();
    $('#box_confirm').jqmAddClose($('.btn_Cancel'));
    // End call box_confirm

    // Bind event click button Clear All
    $("#btclearall").click(function () {
        $("#fitlers").find(".itemfilter").each(function (index) {
            if ($(this).attr("id") != "itemfiltertemplate") {
                $(this).remove();
            }
            alertnames.splice(0, alertnames.length);
            alertFilter.alertname = alertnames;

            languageids.splice(0, languageids.length);
            alertFilter.languageid = languageids;

            countryids.splice(0, countryids.length);
            alertFilter.countryid = countryids;

            campaignids.splice(0, campaignids.length);
            alertFilter.campaignid = campaignids;

            messagebodys.splice(0, messagebodys.length);
            alertFilter.messagebody = messagebodys;

            bindDataByFilter();
        })
        $("#fitlers").css("height", 4);
    });
    // End Bind event click button Clear All
    // Bind event click button Go
    $('#btnGo').click(function () {
        $('#view_summary').addClass('hide');
        if ($("#filterSearch").val() != "") {
            addItemFilterName($("#filterSearch").val());
            //alert names to filter

            alertnames.push($("#filterSearch").val());
            alertFilter.alertname = alertnames;
            $("#filterSearch").val("");
        }
        if ($("#txtMessage").val() != "") {
            addItemFilterMessage($("#txtMessage").val());
            //messagebody to filter

            messagebodys.push($("#txtMessage").val());
            alertFilter.messagebody = messagebodys;
            $("#txtMessage").val("");
        }
        if ($(".campaign input:checked").length > 0) {
            var arr = $(".campaign input:checked").getCheckboxVal();
            var arrName = $(".campaign input:checked").getCheckboxName();
            campaignids.splice(0, campaignids.length);
            //campaign to filter
            for (i = 0; i < arrName.length; i++) {
                campaignids.push(arrName[i]);
            }
            alertFilter.campaignid = campaignids;

            addItemFilterCampaign(arr.join(' OR '));
        }
        if ($(".countries input:checked").length > 0) {
            var arr = $(".countries input:checked").getCheckboxVal();
            var arrName = $(".countries input:checked").getCheckboxName();
            //country to filter
            countryids.splice(0, countryids.length);
            for (i = 0; i < arrName.length; i++) {
                countryids.push(arrName[i]);
            }
            alertFilter.countryid = countryids;
            addItemFilterCountry(arr.join(' OR '));
        }
        if ($(".language input:checked").length > 0) {
            var arr = $(".language input:checked").getCheckboxVal();
            var arrName = $(".language input:checked").getCheckboxName();
            //language to filter
            languageids.splice(0, languageids.length);
            for (i = 0; i < arrName.length; i++) {
                languageids.push(arrName[i]);
            }
            alertFilter.languageid = languageids;
            addItemFilterLanguage(arr.join(' OR '));
        }
        bindDataByFilter();

    });
    // End Bind event click button Go

    // Bind event change drop down list Filter
    $('#ddlFilter').change(function () {
        if ($(this).val() == "Name") {
            $('.type_filter').addClass('hide');
            $('#AlertName').removeClass('hide');
            $('#lblFilter').text('Contains');
        }
        if ($(this).val() == "Campaign") {
            $('.type_filter').addClass('hide');
            $('.ddlcampaign').removeClass('hide');
            $('.ddlcampaign').css('display', 'inline-block');
            $('#lblFilter').text('Is');
        }
        if ($(this).val() == "Country") {
            $('.type_filter').addClass('hide');
            $('.ddlcountries').removeClass('hide');
            $('.ddlcountries').css('display', 'inline-block');
            $('#lblFilter').text('Is');
        }
        if ($(this).val() == "Language") {
            $('.type_filter').addClass('hide');
            $('.ddllanguage').removeClass('hide');
            $('.ddllanguage').css('display', 'inline-block');
            $('#lblFilter').text('Is');
        }
        if ($(this).val() == "Message") {
            $('.type_filter').addClass('hide');
            $('#Message').removeClass('hide');
            $('#lblFilter').text('Contains');
        }
    });
    // End Bind event change drop down list Filter

    setMonthView();
    //var d = new Date();
    //var currdate = format2Digi(d.getDate()) + "/" + format2Digi(d.getMonth() + 1) + "/" + d.getFullYear();
    //getAlertCollectionByDay(currdate);
    getAllAlertInADay(new Date());

    // End Document Ready

    // Function format number
    function format2Digi(num) {
        if (num > 9) return num
        else return "0" + num;
    }
    // End Function format number

    $("#calendarMonthView").click(function () {
        setMonthView();
    });

    $("#calendarWeekView").click(function () {
        setWeekView();
    });

    // Function Set Month View for Expand Calendar
    function setMonthView() {
        // Set color for the selected 
        $('#calendarMonthView').css('color', '#76c5eb');
        $('#calendarWeekView').css('color', '#595959');
        $("#divDatePicker").html('');
        var fullDate = new Date()
        var twoDigitMonth = ((fullDate.getMonth().length + 1) === 1) ? (fullDate.getMonth() + 1) : '0' + (fullDate.getMonth() + 1);
        var currentDate = fullDate.getDate() + "/" + twoDigitMonth + "/" + fullDate.getUTCFullYear();
        var alertInstances = null;
        var firstDayOfMonth = new Date();
        var lastDayOfMonth = new Date();
        $('#divDatePicker').DatePicker({
            flat: true,
            lastSel: true,
            date: currentDate,
            current: currentDate,
            format: 'd/m/Y',
            calendars: 1,
            mode: 'single',
            prev: '&nbsp;',
            next: '&nbsp;',
            dayName: 'daysShort',
            id: '',
            view: 'days',
            onMonthYearChanged: function (fdate, ldate) {
                //get data from json and but all event into a array here
                alertInstances = null;
                firstDayOfMonth = fdate;
                lastDayOfMonth = ldate;
                var itemCount = 0;
                var alertFilter = new Object();
                alertFilter.startdate = format("{0}-{1}-{2} {3}:{4}:{5}", fdate.getFullYear(), fdate.getMonth() + 1, fdate.getDate(), "00", "00", "00");
                alertFilter.enddate = format("{0}-{1}-{2} {3}:{4}:{5}", ldate.getFullYear(), ldate.getMonth() + 1, ldate.getDate(), 23, 59, 59);

                $.ajax({
                    //url: gb_servicePath + '/alertinstance/list.json',
                    url: gb_servicePath + 'alertinstance/list/summary.json',
                    crossDomain: "true",
                    type: "POST",
                    contentType: 'application/json; charset=utf-8',
                    traditional: true,
                    data: JSON.stringify(alertFilter),
                    dataType: 'json',
                    success: function (data) {
                        if (data.StatusCode == 200) {
                            alertInstances = data.ReturnData;
                            while (fdate <= ldate) {
                                var strid = ".date_" + fdate.getDate() + "_" + fdate.getMonth() + "_" + fdate.getFullYear();
                                var tempStrid = "date_" + fdate.getDate() + "_" + fdate.getMonth() + "_" + fdate.getFullYear();
                                var item = $('#divDatePicker').find(".datepickerContainer").find(strid);
                                //var item = $("#" + thisId).find(strid);
                                if (item != null && item.length > 0) {

                                    var itemCount = getCountAlertInDate(fdate, alertInstances);
//                                    if (itemCount > 0)
//                                        item[0].attributes[0].nodeValue = item[0].attributes[0].nodeValue.toString().replace('datepickerSelected', '');

                                    if (itemCount == 1) {
                                        item[0].attributes[0].nodeValue += ' day1';
                                    }
                                    else if (itemCount == 2) {
                                        item[0].attributes[0].nodeValue += ' day2';
                                    }
                                    else if (itemCount >= 3) {
                                        item[0].attributes[0].nodeValue += ' day3';
                                    }
                                }

                                fdate.addDays(1);
                            }
                        }
                        return true;
                    },
                    error: function (jqXHR, textStatus, xerror) {
                        if (isBug) {
                            alert("Error in " + gb_servicePath + " alertinstance/list/summary.json -> " + xerror);
                        }
                    }
                });
                //End getdata
                return false;
            },
            ///            
            onChange: function (formated, dates) {
                getAllAlertInADay(dates);
            },
            starts: 1
        });
    };
    // End Function Set Month View

    //Get number of instance which one has month and date equal date parameter from alertInstances
    function getCountAlertInDate(date, alertInstances) {
        if (alertInstances == null) return 0;
        var count = 0;
        for (i = 0; i < alertInstances.length; i++) {
            //var dateOnInstance = alertInstances[i].AlertInstanceSummary.AlertCollectionSummary.StartTime.substr(6).replace(')', '').replace('/', '');
            var dateOnInstance = alertInstances[i].SendDate.substr(6).replace(')', '').replace('/', '');
            var sendTime = new Date(parseInt(dateOnInstance));
            if (sendTime.getUTCMonth() == date.getMonth() && sendTime.getUTCDate() == date.getDate()) {
                count += 1;
            }
        }
        return count;
    }
    //end - Get number of instance

    //Add new extension method into Date datatype
    Date.prototype.addNDays = function (days) {
        var date = new Date(this.valueOf());
        date.setDate(date.getDate() + days);
        return date;
    }
    //End - cAdd new extension method into Date datatype

    var timeDays = new Array();
    var timeMonth = new Array();
    //Create an Array that stored 24 hours of all days from startDate-> endDate.
    //This array used to validate a day will be added an event into calendar
    function CreateTimeZones(startDate, endDate) {
        timeDays = new Array();
        if (startDate == null) return;
        for (i = 0; i < 8; i++) {
            var sDate = startDate.addNDays(i);
            if (sDate > endDate) continue;
            for (k = 0; k < 24; k++) {
                var zone = new Object();
                zone.start = new Date(sDate.getUTCFullYear(), sDate.getMonth(), sDate.getDate(), k, 0, 0);
                zone.numberOfItems = 0;
                timeDays.push(zone);
            }
        }
    }
    //end - CreateTimeZones

    function CreateTimeZonesByMonth(startDate, endDate) {
        timeMonth = new Array();
        if (startDate == null) return;
        var i = 0;
        var sDate = startDate.addNDays(i);
        while (sDate <= endDate) {
            var zone = new Object();
            zone.start = new Date(sDate.getUTCFullYear(), sDate.getMonth(), sDate.getDate(), 0, 0, 0);
            zone.numberOfItems = 0;
            timeMonth.push(zone);
            i++;
            sDate = startDate.addNDays(i);
        }
    }

    // Function Set Week view for small calendar
    function setWeekView() {
        // Set color for calendar_cursor_pointer
        $('#calendarWeekView').css('color', '#76c5eb');
        $('#calendarMonthView').css('color', '#595959');

        $("#divDatePicker").html('');
        var date = new Date();
        var d = date.getDate();
        var m = date.getMonth();
        var y = date.getUTCFullYear();

        $('#divDatePicker').fullCalendar({
            header: {
                left: 'prev',
                center: 'title',
                right: 'next'
            },
            allDaySlot: false,
            defaultView: 'agendaWeek',
            editable: true,
            selectable: false,
            slotMinutes: 360,
            firstDay: 1,
            dayClick: function (date, allDay, jsEvent, view) {
                getAllAlertInADay(date);
            },
            events: function (start, end, callback) {
                var alertFilter = new Object();
                alertFilter.startdate = start.getUTCFullYear() + "-" + (start.getMonth() + 1) + "-" + start.getDate(); // +" 00:00:00";
                alertFilter.enddate = end.getUTCFullYear() + "-" + (end.getMonth() + 1) + "-" + end.getDate(); // +" 23:59:59";
                $.ajax({
                    //Todo: Need to use only one call only, for big calendar and the small calendar
                    url: gb_servicePath + '/alertinstance/list.json',
                    crossDomain: "true",
                    type: "POST",
                    contentType: 'application/json; charset=utf-8',
                    traditional: true,
                    data: JSON.stringify(alertFilter),
                    dataType: 'json',
                    success: function (data) {
                        if (data.StatusCode == 200) {
                            var events = [];
                            if (data.ReturnData != null) {
                                CreateTimeZones(start, end);
                                $.each(data.ReturnData, function (i, val) {
                                    var date = val.AlertInstanceSummary.StartDate.substr(6).replace(')', '').replace('/', '');
                                    var sendTime = new Date(parseInt(date));
                                    if (canAddEvent(sendTime)) {
                                        events.push({
                                            title: val.Name,
                                            start: new Date(sendTime.getUTCFullYear(), sendTime.getMonth(), sendTime.getDate(), sendTime.getUTCHours(), 0),
                                            end: new Date(sendTime.getUTCFullYear(), sendTime.getMonth(), sendTime.getDate(), sendTime.getUTCHours(), 59),
                                            allDay: false
                                        });
                                    }
                                });

                                getAllAlertInADay(new Date());
                            }
                            callback(events);
                        }
                    },
                    error: function (jqXHR, textStatus, xerror) {
                        if (isBug) {
                            alert("Error in " + gb_servicePath + " alertinstance/list/summary.json -> " + xerror);
                        }
                    }
                });
            },
            eventRender: function (event, element) {

                var timeDay = getTimeDay(event.start);

                if (timeDay.numberOfItems == 2) {
                    element.removeClass("fc-event-skin");
                    element.removeClass("fc-event-skin1");
                    element.addClass("fc-event-skin2");
                }
                else {
                    if (timeDay.numberOfItems >= 3) {
                        element.removeClass("fc-event-skin");
                        element.removeClass("fc-event-skin2");
                        element.removeClass("fc-event-skin2");
                        element.addClass("fc-event-skin3");
                    }
                }
            }
        });
    }
    // End Function Set Week view

    //This function used to validate a Date
    //If this date existed in the array, it does not allow to add an event into calendar and incrise number of date like it to ONE
    //If this date does not exit, it allow to add an event and incrise number of date like it to ONE
    function canAddEvent(date) {
        for (i = 0; i < timeDays.length; i++) {
            if (timeDays[i].start < date) continue;
            var cDate = timeDays[i];
            if (timeDays[i].start.getUTCHours() > date.getUTCHours()) {
                cDate = timeDays[i - 1];
            }
            cDate.numberOfItems++;
            if (cDate.numberOfItems == 1) {
                return true;
            }
            else {
                return false;
            }
        }
        return true;
    }
    //End- This function used to validate a Date

    function canAddEventIntoDay(date) {
        for (i = 0; i < timeMonth.length; i++) {
            if (timeMonth[i].start < date) continue;
            var cDate = timeMonth[i];
            if (timeMonth[i].start.getDate() > date.getDate()) {
                cDate = timeMonth[i - 1];
            }
            cDate.numberOfItems++;
            if (cDate.numberOfItems == 1) {
                return true;
            }
            else {
                return false;
            }
        }
        return true;
    }

    //This function use to get a day from array when calendar render an event
    //Cbjective: to check numberOfItems field, from that we will decide to but a skin for the event.
    function getTimeDay(date) {
        for (i = 0; i < timeDays.length; i++) {
            if (timeDays[i].start < date) continue;
            var cDate = timeDays[i];
            if (timeDays[i].start.getUTCHours() > date.getUTCHours()) {
                cDate = timeDays[i - 1];
            }
            return cDate;
        }
        return null;
    }
    //End - getTimeDay

    function getTimeDayOfMonth(date) {
        for (i = 0; i < timeMonth.length; i++) {
            if (timeMonth[i].start < date) continue;
            var cDate = timeMonth[i];
            if (timeMonth[i].start.getDate() > date.getDate()) {
                cDate = timeMonth[i - 1];
            }
            return cDate;
        }
        return null;
    }

    //this method would be get alerts from server in hole the date and return number of alerts.
    function countAlertsInADay(date) {
        var alertFilter = new Object();
        alertFilter.startdate = format("{0}-{1}-{2} {3}:{4}:{5}", date.getUTCFullYear(), date.getMonth() + 1, date.getDate(), "00", "00", "00");
        alertFilter.enddate = format("{0}-{1}-{2} {3}:{4}:{5}", date.getUTCFullYear(), date.getMonth() + 1, date.getDate(), 23, 59, 59);
        $.ajax({
            url: gb_servicePath + '/alertinstance/list/summary.json',
            crossDomain: "true",
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            traditional: true,
            data: JSON.stringify(alertFilter),
            dataType: 'json',
            success: function (data) {
                if (data.StatusCode == 200) {

                    // alert('data lenght: ' + data.ReturnData.length);

                    if (data.ReturnData != null) {
                        return data.ReturnData.length;
                    } else {
                        return 0;
                    }
                }
            },
            error: function (jqXHR, textStatus, xerror) {
                if (isBug) {
                    alert("Error in " + gb_servicePath + " alertinstance/list/summary.json -> " + xerror);
                }
                return 0;
            }
        });

        return 0;
    }
    //End - this method would be get alerts from server in hole the date and return number of alerts.

    //get alert from server in hold the date and bind to summary box
    // Get by selected date.
    function getAllAlertInADay(date) {
        $('#eventItems').jScrollPane({ animateScroll: true });
        $('#view_summary').addClass('hide');
        var alertFilter = new Object();
        alertFilter.startdate = format("{0}-{1}-{2} {3}:{4}:{5}", date.getUTCFullYear(), date.getMonth() + 1, date.getDate(), "00", "00", "00");
        alertFilter.enddate = format("{0}-{1}-{2} {3}:{4}:{5}", date.getUTCFullYear(), date.getMonth() + 1, date.getDate(), 23, 59, 59);
        $.ajax({
            //url: gb_servicePath + '/alertinstance/list.json', 
            url: gb_servicePath + 'alertinstance/list/summary.json',
            crossDomain: "true",
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            traditional: true,
            data: JSON.stringify(alertFilter),
            dataType: 'json',
            success: function (data) {
                if (data.StatusCode == 200) {
                    $("#eventByDayLoading").css("display", "none");
                    //$("#divEventByDay").find(".jspPane").empty();
                    $("#eventItems .cal_select").remove();
                    if (data.ReturnData != null) {
                        $.each(data.ReturnData, function (i, val) {
                            //var date = val.AlertInstanceSummary.AlertCollectionSummary.StartTime.substr(6).replace(')', '').replace('/', '');
                            //var sendTime = new Date(parseInt(date));
                            var dateOnInstance = val.SendDate.substr(6).replace(')', '').replace('/', '');
                            var sendTime = new Date(parseInt(dateOnInstance));
                            
                            var displayText = format("{0}:{1} {2}", format2Digi(sendTime.getUTCHours()), format2Digi(sendTime.getUTCMinutes()),
                            val.Name);
                            var o = $('<div class="cal_select">' + displayText + '</div>');
                            if (i % 2 == 1) {
                                o.addClass("item2");
                            } else {
                                o.addClass("item1");
                            }
                            o.attr("id", val.ID);

                            $("#eventItems .jspPane").append(o);


                        });
                        $('#eventItems').jScrollPane({ animateScroll: true });
                    };

                    //$('.classdivEventByDay').jScrollPane.defaults.animateScroll = true;

                }
                //$('.divEventByDay').jScrollPane({ animateScroll: true });

            },
            error: function (jqXHR, textStatus, xerror) {
                if (isBug) {
                    alert("Error in alertinstance/list/summary.json -> " + xerror);
                }
            }
        });
    }
    //end - get alert from server in hold the date and bind to summary box

    $('.cal_select').live("click", function () {

        $('.rows_alert').removeClass('rows_alert_hover');
        $('.cal_select').removeClass('rows_alert_hover_daysummary');
        $('.bar').addClass('hide');
        $('#view_summary').removeClass('hide');
        $('#view_summary').css('margin-top', '265px');
        selectedRowKey = $(this).attr("id");

        $(this).addClass('rows_alert_hover_daysummary');
        $('.list_mess_main').remove();
        GetDetailSummary(selectedRowKey);
        $('#content_mess').jScrollPane({ animateScroll: true });

    });

    //this is extension method. [how to use: var str=format("day is:{0}", 15);] str would be "day is: 15"
    function format(str) {
        for (i = 1; i < arguments.length; i++) {
            str = str.replace("{" + (i - 1) + "}", arguments[i]);
        }
        return str;
    }
    //end - this is extension method.

    // Function Add Item Filter Country
    function addItemFilterCountry(str) {
        var o = $("#itemfiltertemplate").clone();
        $(o).find(".filertext").html('Country IS ' + str);
        $(o).attr("id", "itemFilterCountry");
        if ($('#itemFilterCountry').length) {
            $("#itemFilterCountry .filertext").html('Country IS ' + str);
        }
        else {
            $("#fitlers").append(o);
        }
        $(o).find(".btfilterclose").click(function () {
            $(this).parent().remove();
            countryids.splice(0, countryids.length);
            alertFilter.countryid = countryids;
            bindDataByFilter();
        });

    }
    // End Function Add Item Filter Country

    // Function Add Item Filter Language
    function addItemFilterLanguage(str) {
        var o = $("#itemfiltertemplate").clone();
        $(o).find(".filertext").html('Language IS ' + str);
        $(o).attr("id", "itemFilterLanguage");
        if ($('#itemFilterLanguage').length) {
            $("#itemFilterLanguage .filertext").html('Language IS ' + str);
        }
        else {
            $("#fitlers").append(o);
        }
        $(o).find(".btfilterclose").click(function () {
            $(this).parent().remove();
            languageids.splice(0, languageids.length);
            alertFilter.languageid = languageids;
            bindDataByFilter();
        });

    }
    // End Function Add Item Filter Language

    // Function Add Item Filter Campaign
    function addItemFilterCampaign(str) {
        var o = $("#itemfiltertemplate").clone();
        $(o).find(".filertext").html('Campaign IS ' + str);
        $(o).attr("id", "itemFilterCampaign");
        if ($('#itemFilterCampaign').length) {
            $("#itemFilterCampaign .filertext").html('Campaign IS ' + str);
        }
        else {
            $("#fitlers").append(o);
        }
        $(o).find(".btfilterclose").click(function () {
            $(this).parent().remove();
            campaignids.splice(0, campaignids.length);
            alertFilter.campaignid = campaignids;
            bindDataByFilter();
        });

    }
    // End Function Add Item Filter Campaign

    // Function Add Item Filter Name
    function addItemFilterName(str) {
        var o = $("#itemfiltertemplate").clone();
        $(o).find(".filertext").html('Name contains "' + str + '"');
        $(o).attr("id", "itemFilterName");
        if ($('#itemFilterName').length) {
            $("#itemFilterName").append($(o).find(".filertext").html('&nbsp;OR "' + str + '"'));
        }
        else {
            $("#fitlers").append(o);
        }
        $(o).find(".btfilterclose").click(function () {
            $(this).parent().remove();
            alertnames.splice(0, alertnames.length);
            alertFilter.alertname = alertnames;
            bindDataByFilter();
        });
    }
    // End Function Add Item Filter Name

    // Function Add Item Filter Message
    function addItemFilterMessage(str) {
        var o = $("#itemfiltertemplate").clone();
        $(o).find(".filertext").html('Message contains "' + str + '"');
        $(o).attr("id", "itemFilterMessage");
        if ($('#itemFilterMessage').length) {
            var filterFirsr = $("#itemFilterMessage .filertext:first").text();
            $("#itemFilterMessage").append($(o).find(".filertext").html('&nbsp;Or "' + str + '"'));
        }
        else {
            $("#fitlers").append(o);
        }
        $(o).find(".btfilterclose").click(function () {
            $(this).parent().remove();
            messagebodys.splice(0, messagebodys.length);
            alertFilter.messagebody = messagebodys;
            bindDataByFilter();
        });

    }
    // End Function Add Item Filter Message

    // Function Show box Confirm
    function showModal(bo) {
        if (bo) {
            if ($(".rows_alert_hover").find(".col_frequency").html() != "None") {
                $("#btnOk_confirm3").css("display", "block");
                $('#box_confirm').css("width", "320 !important");
            } else {
                $("#btnOk_confirm3").css("display", "none");
                $('#box_confirm').css("width", 240);
            }
            $('#box_confirm').jqmShow();
        } else {
            $('#box_confirm').jqmHide();
        }
    }
    // End Function Show box Confirm

});


// Function format number
function format2Digi(num) {
    if (num > 9) return num
    else return "0" + num;
}
// End Function format number
